package uk.ac.open.kmi.dyniqx.repositories;

import java.net.URLEncoder;
import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import org.apache.log4j.Logger;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import uk.ac.open.kmi.dyniqx.storages.Storage;
import uk.ac.open.kmi.dyniqx.wrappers.QueryWrapper;

public class IntuteRepository implements Repository {

	private Storage storage;
	
	public Logger logger = Logger.getLogger("uk.ac.open.kmi.dyniqx.repositories.IntuteRepository");
	
	public IntuteRepository() {
		this.logger.debug("IntuteRepository instance created.");
	}
	
	@SuppressWarnings("unchecked")
	public void performQuery(String queryString) {
		
		String baseUrl = "http://www.intute.ac.uk/include2/cgi-bin/include_search2.pl?q=";
		
		/* Open University proxy Settings */
 
		System.getProperties().put( "proxySet", "true" );
		System.getProperties().put( "proxyHost", "wwwcache" );
		System.getProperties().put( "proxyPort", "80" );
		System.setProperty("java.net.useSystemProxies","true");
		
		SAXBuilder parser = new SAXBuilder();

		try {

			Document doc = parser.build(baseUrl + URLEncoder.encode(queryString, "UTF-8"));
			Element root = doc.getRootElement();
			String count = XPath.newInstance("/rss/channel/opensearch:totalResults").valueOf(root);
	    	WebContext wctx = WebContextFactory.get();
	    	QueryWrapper newQuery = new QueryWrapper(queryString, "Int", Integer.parseInt(count), 0);
	    	
	    	this.storage.getQueryWrapper().add(newQuery);
	    	
	    	Thread t = new IntuteThread(this.storage, wctx, queryString, Integer.parseInt(count));
	    	t.setName("INT" + "-" + wctx.getSession().getId() + "-" + (System.currentTimeMillis() % 1000000));
	    	t.start();
	    		    	
	    	this.storage.updateGrid();	    		    	
			
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void setStorage(Storage storage) {
		this.storage = storage;
	}	
	
	public Storage getStorage() {
		return this.storage;
	}
}
